package 极客算法训练营.chapter06;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class 二叉树的中序遍历 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution1 {
        private List<Integer> list = new ArrayList<>();

        public List<Integer> inorderTraversal(TreeNode root) {
            recursionTree(root);
            return list;
        }

        public void recursionTree(TreeNode node) {
            //递归终止条件
            if (node == null) return;
            //递归执行体
            recursionTree(node.left);
            list.add(node.val);
            recursionTree(node.right);
        }
    }

    class Solution2 {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            Deque<TreeNode> stack = new LinkedList<>();
            while (root != null || !stack.isEmpty()) {
                //一直向左遍历
                while (root != null) {
                    stack.push(root);
                    root = root.left;
                }
                //找到上一个结点
                TreeNode pop = stack.pop();
                root = pop;
                res.add(root.val);
                //向右遍历
                root = root.right;
            }
            return res;
        }
    }

    class Solution3 {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            while (root != null) {
                if (root.left != null) {
                    //维护一个关键性的关系维护指针
                    TreeNode predecessor = null;
                    //先找到在中序遍历中该节点的前置节点predecessor
                    predecessor = root.left;
                    while (predecessor.right != null && predecessor.right != root) {
                        predecessor = predecessor.right;
                    }
                    //前置结点已找到，如果是第一次遍历就创建连接；如果是第二次遍历就断开连接
                    //第一次遍历是左探，第二次遍历是回调
                    if (predecessor.right == null) {
                        predecessor.right = root;
                        //关系已维护，当前结点可放心左探
                        root = root.left;
                    } else {
                        res.add(root.val);
                        predecessor = null;
                        root = root.right;
                    }

                } else {//没有左孩子
                    res.add(root.val);
                    root = root.right;
                }
            }
            return res;
        }
    }
}
